package com.open.capacity.trade.service.impl;

import com.open.capacity.common.exception.service.ServiceException;
import com.open.capacity.common.model.Records;
import com.open.capacity.common.util.PageUtil;
import com.open.capacity.common.web.PageResult;
import com.open.capacity.common.web.Result;
import com.open.capacity.trade.dao.RecordsDao;
import com.open.capacity.trade.feign.TradeFeignClient;
import com.open.capacity.trade.model.RecordsExcel;
import com.open.capacity.trade.service.RecordsService;
import com.open.capacity.trade.vo.TradeRecordsVo;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Lookup;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
@Slf4j
@Service
public class RecordsServiceImpl implements RecordsService {
    @Autowired
    private RecordsDao recordsDao;
    //	测试
    @Autowired
    private TradeFeignClient tradeFeignClient;

    @Override
    public PageResult<Records> findRecords(Map<String, Object> params) throws ServiceException {
        try {
            PageResult<Records> records = recordsDao.findAllP(params);
            return records;
        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }

    @Override
    public PageResult<Records> findRecords() throws ServiceException {
        try {
            PageResult<Records> records = recordsDao.findAll();
            return records;
        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }

    @Override
    public PageResult<Records> findAll() {
        try {
//            PageResult<Records> records= recordsDao.findAll();
            List<Records> list = recordsDao.findAlls();
            PageResult<Records> objectPageResult = new PageResult<>();
            objectPageResult.setData(list);
//            todo
//            类型不能转换
            return objectPageResult;
        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }

    /*查询所有交易记录*/
    @Override
    public PageResult<TradeRecordsVo> findAllRecords(Map<String, Object> params) throws ServiceException {
            try {
                //由于没有初始化数据，就先在页面展示数据时进行数据的导入
                //调用其它模块的feignClient实现远程调用
                //再将得到的数据进行导入表中
                //之后数据就是动态插入
//                Records records = new Records();
//                this.insertRecords(records);
                int total = recordsDao.count(params);
                List<TradeRecordsVo> list = Collections.emptyList();
                if (total > 0) {
                    PageUtil.pageParamConver(params, true);
                    list = recordsDao.findAllRecords(params);
                }
                return PageResult.<TradeRecordsVo>builder().data(list).code(0).count((long) total).build();
            } catch (Exception e) {
                throw new ServiceException(e);
            }
        }

    @Transactional
    @Override
    public Result updateEnabled(Map<String, Object> params) throws ServiceException {
        try{
            Long id = MapUtils.getLong(params, "id");
            Long recordsId=MapUtils.getLong(params,"recordsId");
            Boolean enabled = MapUtils.getBoolean(params, "enabled");
            Integer conduct= enabled ? 0:1;

            Records records = recordsDao.findById(id,recordsId);
            if (records == null) {
                return Result.failed("交易记录不存在");
                //throw new IllegalArgumentException("用户不存在");
            }
            records.setConduct(conduct);
            records.setUpdateTime(new Date());

            int i = recordsDao.updateOrEnabled(records);
            log.info("修改交易记录：{}", records);

            return i > 0 ? Result.succeed(records, "更新成功") : Result.failed("更新失败");
        }catch (Exception e){
            throw new ServiceException(e);
        }
    }

    @Transactional
    @Override
    public void deleteRecords(Long id,Long recordsId) throws ServiceException {
        try {
            Records records = recordsDao.findById(id,recordsId);
            recordsDao.deleteRecords(id,recordsId);
            log.info("删除交易记录：{}", records);
        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }

    /**
     * 修改交易记录表
     * @param records 能够修改的参数只有招聘人数people，与单价industry
     * @return
     * @throws ServiceException
     */
    @Override
    public Result saveOrUpdate(Records records) throws ServiceException {
        try{
            Integer conduct=recordsDao.findConduct(records);
            if (conduct==0){
            records.setUpdateTime(new Date());
            int result=0;
            result=recordsDao.updateOrEnabled(records);
            return result > 0 ? Result.succeed( "操作成功") : Result.failed("操作失败");
            }else{
                return conduct == 1 ? Result.succeed("已停止招聘，无法修改"):Result.failed("逻辑问题");
            }
        }catch (Exception e){
            throw new ServiceException(e);
        }
    }

    @Override
    public List<RecordsExcel> findAllRecordsExcel(Map<String, Object> params) throws ServiceException {
        try {
            List<RecordsExcel> sysUserExcels = new ArrayList<>();
            List<TradeRecordsVo> list = recordsDao.findAllRecords(params);

            for (TradeRecordsVo sysUser : list){
                RecordsExcel sysUserExcel = new RecordsExcel();
                BeanUtils.copyProperties(sysUser,sysUserExcel);
                sysUserExcels.add(sysUserExcel);
            }
            //测试feignClient
//            Records records = new Records();
//            records.setCompanyName("测试feign");
//            records.setPosition("feign测试者");
//            records.setPeople(12);
//            records.setIndustry(12.12);
//            records.setEntrys(2);
//            records.setConduct(0);
//            records.setCreateTime(new Date());
//            tradeFeignClient.insertRecords(records);
            return sysUserExcels;
        } catch (BeansException e) {
            throw new ServiceException(e);
        }
    }

    @Override
    public Result insertRecords(Records records) throws ServiceException {
        //可能会存在线程安全问题，同一时间多个新增
        try{
            Long getTime;
            synchronized (records){
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
                String today=simpleDateFormat.format(new Date());
                String r=today.replaceAll("[[\\s-:punct:]]","");
//                String c=today.replaceAll(" ","");
//                String d=today.replaceAll(":","");
//                today.split(" ");
//                today.split(":");
//                System.out.println(r);
                getTime=Long.valueOf(String.valueOf(r));
            }
            records.setRecordsId(getTime);
            records.setEntrys(0);
            records.setCreateTime(new Date());
            int result=0;
            result=recordsDao.insertRecords(records);
            return result > 0 ? Result.succeed("操作成功") : Result.failed("操作失败");
        }catch (Exception e){
            throw new ServiceException(e);
        }
    }

    @Override
    public Result updateEntry(Records records) throws ServiceException {
        try {
            Records byId = recordsDao.findBy(records);
            if (byId.getConduct()==1){//停止招聘
                return Result.failed("招聘已截止");
            }else{
                if (byId.getEntrys()<byId.getPeople()){//录用人小于招聘人
                    byId.setEntrys(byId.getEntrys()+1);
                    Integer result=recordsDao.updateEntry(byId);
                    return result >0 ? Result.succeed("操作成功") : Result.failed("操作失败");
                }
                else{
                    return Result.failed("招聘人数够了");
                }
            }

        }catch (Exception e){
            throw new ServiceException(e);
        }
    }

    @Override
    public Integer updateEntrys(Records records) {
        Records byId = recordsDao.findBy(records);
        if (byId.getConduct() == 1) {//停止招聘
            return 1;
        } else {
            if (byId.getEntrys() < byId.getPeople()) {//录用人小于招聘人
                byId.setEntrys(byId.getEntrys() + 1);
                Integer result = recordsDao.updateEntry(byId);
                return 0;
            } else {
                return 1;
            }
        }
    }

    @Override
    public Result updateRecordsAccepted(Records records) throws ServiceException {
//  理：查询招聘信息表crm_recruitment中的招聘人数是多少，因为已录人数不得大于招聘人数
        try{
            Records peopleAndEntry=recordsDao.getPeople(records);
            if (peopleAndEntry.getPeople()>peopleAndEntry.getEntrys()){
                peopleAndEntry.setEntrys(peopleAndEntry.getEntrys()+1);
                peopleAndEntry.setUpdateTime(new Date());
                Integer result=recordsDao.updateRecordsAccepted(peopleAndEntry);
                return result > 0? Result.succeed("操作成功"):Result.failed("操作失败");
            }
            return Result.failed("已招满");
        }catch (Exception e){
            throw new ServiceException(e);
        }
    }

    @Override
    public Result updateRecordsBasic(Records records) throws ServiceException {
//  理：如果要修改招聘人数，那就需要判断修改后的招聘人数与已录人数的大小
        try{
            if (records.getPeople()!=null){
                Records peopleAndEntry=recordsDao.getPeople(records);
                if(records.getPeople()>=peopleAndEntry.getEntrys()){
                    records.setUpdateTime(new Date());
                    Integer result=recordsDao.updateRecordsBasic(records);
                    return result > 0? Result.succeed("操作成功"):Result.failed("操作失败");
                }
            }else{
                Records peopleAndEntry=recordsDao.getRecords(records);
                if (peopleAndEntry.getPeople()>peopleAndEntry.getEntrys() && records.getEntrys()!=null){//所需人数大于已录人数
                    records.setEntrys(peopleAndEntry.getEntrys()+records.getEntrys());
                }
                if (peopleAndEntry.getPeople()<=peopleAndEntry.getEntrys()){
                    return Result.failed("操作失败");
                }
                records.setUpdateTime(new Date());
                Integer result=recordsDao.updateRecordsBasic(records);
                return result > 0? Result.succeed("操作成功"):Result.failed("操作失败");
            }
            return null;
        }catch (Exception e){
            throw new ServiceException(e);
        }
    }
}